<?php
	class Tiku extends MY_controller{

		function __construct(){
			parent::__construct();
		}

		function test_volume($subject_id = 0, $test_volume_name = 0, $limit = 0){
			$this->offset = 10;
			if($this->input->post()){
				$limit = 0;
				$post_data = $this->input->post();
				$test_volume_name = $post_data['test_volume_name'] ? urldecode($post_data['test_volume_name']) : 0;
				$subject_id = isset($post_data['subject_id']) ? $post_data['subject_id'] : 0;
			}
			$this->load->model("Topics");
			$conditions = array('subject_id' => $subject_id, 'test_volume_name' => $test_volume_name);
			$this->load->model("Test_volumes");
			$result = $this->Test_volumes->get_test_volume_list($limit, $this->offset, $conditions);
			/*if($result['count'] > 0){
				$conditions['school_id'] = 0;
				foreach ($result['result'] as $key => $value) {
					$conditions['volume_id'] = $value['id'];
					$publish_list = $this->Test_volumes->get_test_volume_publish(0, 0, $conditions);
					if(!empty($publish_list)){
						foreach ($publish_list as $k => $value) {
							$result['result'][$key]['type'][$value['type']] = 1;
						}
					}
				}
			}*/
			// print_r($result['result']);   
			$this->load->library('pagination');
			$page_config['base_url'] = '/tiku/test_volume/' . $subject_id . '/' . $test_volume_name;
			$page_config['total_rows'] = $result['count'];
			$page_config['per_page'] = $this->offset;
			$page_config['uri_segment'] = 5;
			$this->pagination->initialize($page_config);
			$pagination = $this->pagination->create_links();
			/*$subject = $this->Topics->get_subject(0);
			$this->smarty->assign("subject", $subject);*/
			$this->smarty->assign("test_volume_list", $result['result']);
			$this->smarty->assign("conditions", $conditions);
			$this->smarty->assign("action", '组卷列表');
			$this->smarty->assign("pagination", $pagination);
			$this->smarty->display("topic/test_volume.html");
		}

		function get_chapter_list($subject_id = 0){
			$conditions = array();
			if($subject_id > 0){
				$conditions['subject_id'] = $subject_id;
			}
			$chapter_list = $this->Topics->get_chapter($conditions);

			$chapter_list_data_sort = $chapter_list_data = array();
			$code = 0;
			$keys = array();
			if($chapter_list){
				$sort = array();
				foreach ($chapter_list as $key => $value) {
					if($value['parent_id'] == 0){
						$chapter_list_data_sort[$value['id']] = $value;
						$keys[$value['id']] = 1;
						$sort[] = $value['sort'];
						unset($chapter_list[$key]);
					}
				}
				array_multisort($sort, SORT_ASC, $chapter_list_data_sort);
				foreach($chapter_list_data_sort as $key => $value){
					$chapter_list_data[$value['id']] = $value;
				}


				foreach ($chapter_list as $key => $value) {
					if(isset($chapter_list_data[$value['parent_id']])){
						$chapter_list_data[$value['parent_id']]['sub'][$value['id']] = $value;
						unset($chapter_list[$key]);
					}
				}

				if($chapter_list AND $chapter_list_data){
					foreach ($chapter_list_data as $key => $value) {
						if(isset($value['sub'])){
							foreach ($value['sub'] as $k => $v) {
								foreach ($chapter_list as $k1 => $v1) {
									if($k == $v1['parent_id']){
										$chapter_list_data[$key]['sub'][$k]['sub'][$v1['id']] = $v1;
									}
								}
							}
						}
					}
				}
			}
			/*$data = array();
			if(count($keys) > 0){
				ksort($keys);
				foreach ($keys as $k => $v) {
					$data[$k] = $chapter_list_data[$k];
				}
			}*/
			return $chapter_list_data;
		}

		function add_test_volume($test_volume_name = ''){
			$this->load->model("Topics");
			$school_id = 0;
			$teacher_id = 0;

			$post_data = $this->input->post();
			if($post_data){
				if(empty($post_data['template_id'])){
					show_message($this->jump_url, "缺少模版ID");
					exit;
				}

				$template_info = get_field_by_where("tk_test_volume_templates", "*", "id='{$post_data['template_id']}'");
				
				if(!$template_info){
					show_message($this->jump_url, "组卷模版不存在");
					exit;
				}
				if($template_info['school_id'] != $school_id){
					show_message($this->jump_url, "您无法使用该模版");
					exit;
				}

				$test_volume_data['name'] = trim($post_data['name']);
				$test_volume_data['school_id'] = $school_id;
				$test_volume_data['teacher_id'] = $teacher_id;
				// $test_volume_data['subject_id'] = intval($post_data['subject_id']);
				$test_volume_data['topic_source'] = intval($post_data['topic_source']) + 1;
				$test_volume_data['create_topic_type'] = intval($post_data['create_topic_type']);
				$test_volume_data['topic_info'] = !empty($post_data['topic']) ? implode(",", $post_data['topic']) : '';
				$test_volume_data['chapter_id'] = !empty($post_data['chapter_id']) ? implode(",", $post_data['chapter_id']) : '';
				$test_volume_data['template_id'] = intval($post_data['template_id']);

				//系统随机选题
				if($post_data['create_topic_type'] == 1){
					$template_content = json_decode($template_info['content'], true);
					$conditions['school_id'] = $test_volume_data['school_id'];
					// $conditions['subject_id'] = $test_volume_data['subject_id'];
					foreach ($template_content as $key => $value) {
						for ($i=0; $i < $value['number']; $i++) {
							$conditions['notin_ids'] = $test_volume_data['topic_info'];
							$conditions['type'] = $key;
							$rand_data = $this->Topics->get_rand_topic($conditions);
							if($rand_data){
								$test_volume_data['topic_info'][] .= $rand_data['id'];
							}
						}
					}
					if(is_array($test_volume_data['topic_info']) && count($test_volume_data['topic_info']) > 0){
						$test_volume_data['topic_info'] = implode(",", $test_volume_data['topic_info']);
					}else{
						show_message($this->jump_url, "当前科目下没有题目，无法创建组卷");
						exit;
					}
				}else{//自己选题
					if($template_info['total_topic'] != count($post_data['topic'])){
						// echo '您选的题目数量跟组卷模版不符';exit;
					}
				}
				$letter = array('A','B','C','D');
				$topic_list = $this->pretend_topics($test_volume_data);
				// print_r($topic_list);exit;
				$this->smarty->assign("test_volume_data", $test_volume_data);
				$this->smarty->assign("topic_list", $topic_list);
				$this->smarty->assign("letter", $letter);
				$this->smarty->assign("action", '题目预览');
				$this->smarty->display("topic/test_volume_topic_list.html");
			}else{
				$templates = $this->Topics->get_test_volume_templates(0);
				// $this->smarty->assign("subject", $subject);
				$this->smarty->assign("action", '添加组卷');
				$this->smarty->assign("test_volume_name", urldecode($test_volume_name));
				// $this->smarty->assign("chapter_list_data", $chapter_list_data);
				$this->smarty->assign("templates", $templates);
				$this->smarty->assign("menu", "tiku");
				$this->smarty->display("topic/add_test_volume.html");
			}
		}

		//组装题目
		function pretend_topics($test_volume_data = array()){
			$topic_list = array();
			if($test_volume_data){
				$topic_info_list = $this->Topics->get_topic_by_id($test_volume_data['topic_info']);
				if($topic_info_list){
					foreach ($topic_info_list as $key => $value) {
						if($value['type'] == 4 || $value['type'] == 7){
							$analy_result = $this->Topics->get_topic_analys($value['id']);
							if($analy_result){
								$value['result'][$key] = $analy_result;
								foreach ($analy_result as $k => $v) {
									$value['result'][$key][$k]['answer_list'] = $this->Topics->get_topic_analys_result($v['id']);
								}
								$topic_list[$value['type']][] = $value;
							}
						}else{
							$value['result'] = $this->Topics->get_topic_result_by_id($value['id']);
							$topic_list[$value['type']][] = $value;
						}
						/*foreach ($topic_result as $k => $v) {
							if($v['qid'] == $value['id']){
								$value['result'][] = $v;
								unset($topic_result[$k]);
							}
						}*/
					}
				}
			}
			return $topic_list;
		}

		function save_test_volume_template(){
			$school_id = 0;
			$teacher_id = 0;

			$post_data = $this->input->post();
			if(empty($post_data['template_name'])){
				$error = 1;
				$msg = '缺少模版名称';
				echo json_encode(array("error" => $error, "msg" => $msg));exit;
			}
			$template_info = get_field_by_where("tk_test_volume_templates", "id", "template_name='{$post_data['template_name']}' AND teacher_id = $teacher_id");
			if($template_info){
				$error = 1;
				$msg = '模版名重复';
				echo json_encode(array("error" => $error, "msg" => $msg));exit;
			}
			if(isset($post_data['number']) && isset($post_data['fraction'])){
				$data['template_name'] 	= trim($post_data['template_name']);
				$data['school_id'] 		= $school_id;
				$data['teacher_id'] 	= $teacher_id;
				$data['total_fraction'] = 0;
				$data['total_topic'] 	= 0;
				$data['content'] 		= array();
				$data['add_time'] 		= time();
				$tpoic_type = array("1" => "单选题", "2" => "多选题", "3" => "判断题", "4" => "计算分析题", "7" => "不定向选择题", "8" => "名词解释", "9" => "简答题");
				foreach ($post_data['number'] as $key => $value) {
					if($value > 0){
						$data['total_fraction'] += $fraction = $value * $post_data['fraction'][$key];
						$data['total_topic'] += $value;
						$data['content'][$key] = array("name" => $tpoic_type[$key], "number" => $value, "fraction" => $post_data['fraction'][$key]);
					}
				}
				if(count($data['content']) > 0 && $data['total_topic'] > 0){
					$data['content'] = json_encode($data['content']);
					$this->db->insert("tk_test_volume_templates", $data);
					$error = 0;
					$msg = '模版保存成功';
					$template_id = $this->db->insert_id();
					echo json_encode(array("error" => $error, "msg" => $msg, "template_id" => $template_id, 'template_name' => $data['template_name']));exit;
				}else{
					$error = 1;
					$msg = '缺少模版内容';
					echo json_encode(array("error" => $error, "msg" => $msg));exit;
				}
			}else{
				$error = 1;
				$msg = '缺少模版内容';
				echo json_encode(array("error" => $error, "msg" => $msg));exit;
			}
		}
		function get_template_content(){
			$post_data = $this->input->post();
			$template_info = get_field_by_where("tk_test_volume_templates", "content", "id='{$post_data['template_id']}'");
			if($template_info){
				$error = 0;
				echo json_encode(array("error" => $error, "content" => json_decode($template_info['content'])));exit;
			}else{
				$error = 1;
				$msg = '模版不存在';
				echo json_encode(array("error" => $error, "msg" => $msg));exit;
			}
		}

		function get_list($source_type = 0, $chapter_id= 0, $type = 0, $subject_text = 0, $limit = 0){
			$this->load->model("Topics");
			if($this->input->post()){
				$subject_text = $this->input->post('subject_text',TRUE) ? urldecode($this->input->post('subject_text',TRUE)) : 0;
				$type = $this->input->post('type');
				$limit = 0;
			}
			if($chapter_id != 0){
				$chapter_id = str_replace('.', ',', $chapter_id);
			}
			$subject_text = urldecode($subject_text);
			$conditions['source_type'] = $source_type;
			$conditions['chapter_id'] = $chapter_id;
			$conditions['type'] = $type;
			$conditions['subject_text'] = $subject_text;
			$offset = 10;
			$result = $this->Topics->get_topic_list($limit, $offset, $conditions);
			$this->load->library('pagination');
			$current_url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
			if($chapter_id != 0){
				$chapter_id = str_replace(',', '.', $chapter_id);
			}
			$page_config['base_url'] = '/tiku/get_list/' . $source_type . '/' . $chapter_id . '/' . $type . '/' . $subject_text;
			$page_config['total_rows'] = $result['count'];
			$page_config['per_page'] = $offset;
			$page_config['uri_segment'] = 8;
			$this->pagination->initialize($page_config);
			$pagination = $this->pagination->create_links();
			$this->smarty->assign("current_url", $current_url);
			$this->smarty->assign("topic_list", $result['result']);
			$this->smarty->assign("pagination", $pagination);
			$this->smarty->assign("conditions", $conditions);
			$this->smarty->assign("action", '题目列表');
			$this->smarty->display("topic/tlist.html");
		}

		function save_test_volume(){
			$post_data = $this->input->post();
			if($post_data){
				if(isset($post_data['analys'])) unset($post_data['analys']);
				$post_data['add_time'] = time();
				$this->db->insert("tk_test_volumes", $post_data);
				show_message("/tiku/test_volume");
			}
		}

		function save_volume_publish(){
			$post_data = $this->input->post();
			$msg = '';
			$error = 0;

			if(empty($post_data['volume_id'])){
				$error = 1;
				$msg = '缺少组卷ID';
			}
			if(empty($post_data['type'])){
				$error = 1;
				$msg = '缺少发布类型TYPE';
			}
			if(empty($post_data['classes']) && ($post_data['type'] == 3 || $post_data['type'] ==4)){
				$error = 1;
				$msg = '至少需要发布到一个班级';
			}
			if(empty($post_data['timeout'])){
				$error = 1;
				$msg = '未指定考试时长';
			}
			if(empty($post_data['name'])){
				$error = 1;
				$msg = '缺少名称';
			}
			/*if(($post_data['type'] == 3 || $post_data['type'] ==4) && (empty($post_data['start_time']) || empty($post_data['end_time']))){
				$error = 1;
				$msg = '未指定考试时间';
			}*/
			$volume_info = get_field_by_where("tk_test_volumes", "*", "id='{$post_data['volume_id']}'");
			if(empty($volume_info)){
				$error = 1;
				$msg = '组卷数据不存在';
			}
			$post_data['school_id'] = 0;
			$post_data['teacher_id'] = 0;
			if(!empty($post_data['classes'])){
				$post_data['classes'] = implode(",", $post_data['classes']);
			}
			/*if(!empty($post_data['start_time'])){
				$post_data['start_time'] = strtotime($post_data['start_time']);
			}
			if(!empty($post_data['end_time'])){
				$post_data['end_time'] = strtotime($post_data['end_time']);
			}*/
			$post_data['add_time'] = time();
			if($post_data['type'] == 3 || $post_data['type'] == 4){
				$this->load->model('Classo2o_model');
				if($error == 0){
					$this->db->insert("tk_test_volumes_publish", $post_data);
					$user_list = $this->Classo2o_model->get_classes_user_openid($post_data['classes']);
					if($user_list){
						foreach ($user_list as $key => $value) {
							if($post_data['type'] == 3){
								$template_id = 'lqys63GSbWsnbumTU4DfgIQVwuE_2VE_x_gIsUTbWeI';
								$data = array(
											"first" 	=> array("value" => '亲爱的同学，您有新的作业提醒，请查阅。'),
											"keyword1" 	=> array("value" => "-"),
											"keyword2"	=> array("value" => $post_data['name']),
											"keyword3"	=> array("value" => '作业标准完成时长为：' . $post_data['timeout'] . '分钟，请自行计时。'),
											"remark"	=> array("value" => $post_data['prompt'])
										);
							}else{
								$template_id = '6hY9F0nfOfohnpEXtA1OuDMoJePbnGNSdZocNyakFOI';
								$data = array(
											"first" 	=> array("value" => '亲爱的同学，您有新的考试提醒，请查阅。'),
											"keyword1" 	=> array("value" => $post_data['name']),
											"keyword2"	=> array("value" => '-'),
											"keyword3"  => array("value" => "不限"),
											"keyword4"	=> array("value" => $value['course_name']),
											"keyword5"	=> array("value" => '互联网自主考试'),
											"remark"	=> array("value" => '考试标准完成时长为：' . $post_data['timeout'] . '分钟，请自行计时。' . $post_data['prompt'])
										);
							}
							$this->wx_notice($value['open_id'], $template_id, $data);
						}
					}
				}else{
					$this->smarty->assign("class_list", '');
					$this->smarty->assign("volume_id", $post_data['volume_id']);
					$this->smarty->assign("type", $post_data['type']);
					$classes = $this->Classo2o_model->get_class_list(0);
					$this->smarty->assign("classes", $classes);
				}
				$this->smarty->assign("ok", 1);
				$this->smarty->assign("error", $error);
				$this->smarty->assign("msg", $msg);
				$this->smarty->assign("type", $post_data['type']);
				$this->smarty->display("tiku/test_volume_publish.html");
			}else{
				$this->db->insert("tk_test_volumes_publish", $post_data);
				if($post_data['type'] == 1){
					$result['msg'] = "已发布到考情速递";
				}else if($post_data['type'] == 2){
					$result['msg'] = "已发布到真题冲刺";
				}
				$result['error'] = 0;
				echo json_encode($result);
			}
			// show_message("/tiku/save_volume_publish/1");
		}

		function delete_volume($volume_id = 0){
			$volume_info = get_field_by_where('tk_test_volumes', "id,school_id", "id='{$volume_id}'");
			if(!$volume_info){
				show_message("/tiku/test_volume", "数据不存在");exit;
			}
			if($volume_info['school_id'] != 0){
				show_message("/tiku/test_volume", "该组卷为第三方学校发布的，无法删除");exit;
			}
			$this->load->model("Test_volumes");
			$this->Test_volumes->delete_volume_data($volume_id);
			show_message("/tiku/test_volume", "删除成功");exit;
		}
	}
